<script setup lang="ts">
import ace from "ace-builds";
import "ace-builds/src-min-noconflict/theme-chrome";
import "ace-builds/src-min-noconflict/mode-json5";
import { ref, onMounted, watch } from "vue";
import { nextTick } from "process";

defineOptions({
  name: "AceEditor"
});
defineExpose({
  getValue,
  setValue
});
const editor = ref();
const aceRef = ref();
const props = defineProps({
  configJson: {
    type: Object || Array,
    default: () => ({})
  }
});
watch(
  () => props.configJson,
  newVal => {
    if (!editor.value) {
      nextTick(() => {
        //JSON.stringify 第3个参数表示按照4个字符缩进
        setValue(newVal);
      });
    } else {
      setValue(newVal);
    }
  }
);
onMounted(() => {
  nextTick(() => {
    editor.value = ace.edit(aceRef.value, {
      maxLines: 28,
      minLines: 28,
      fontSize: 14,
      theme: "ace/theme/chrome",
      mode: "ace/mode/json5",
      tabSize: 4,
      readOnly: false
    });
    setValue(props.configJson);
  });
});
function setValue(val) {
  editor.value.setValue(JSON.stringify(val, null, 4));
  editor.value.clearSelection();
}
function getValue() {
  try {
    return JSON.parse(editor.value.getValue());
  } catch (error) {
    return {};
  }
}
</script>

<template>
  <div ref="aceRef" class="ace" />
</template>

<!-- <style lang="scss" scoped></style> -->
